//
//  SCCollectionViewColorFlowLayout.m
//  Shuaiche
//
//  Created by 党帅 on 2019/5/14.
//  Copyright © 2019 zzs. All rights reserved.
//


#import "SCCollectionViewColorFlowLayout.h"

static NSString *const kSCCollectionViewColorBgKind = @"colorBg";

@interface UICollectionViewColorLayoutAttributes : UICollectionViewLayoutAttributes
@property (nonatomic, strong) UIColor *sectionBgColor;
@property(nonatomic, assign) CGFloat sectionCornerRadius;
@end

@implementation UICollectionViewColorLayoutAttributes

@end

@interface UICollectionSectionColorReusableView : UICollectionReusableView

@end

@implementation UICollectionSectionColorReusableView

- (void)applyLayoutAttributes:(UICollectionViewLayoutAttributes *)layoutAttributes {
    [super applyLayoutAttributes:layoutAttributes];
    if ([layoutAttributes.representedElementKind isEqualToString:kSCCollectionViewColorBgKind]) {
        UICollectionViewColorLayoutAttributes *layout = (UICollectionViewColorLayoutAttributes *)layoutAttributes;
        self.backgroundColor = layout.sectionBgColor;
        if (layout.sectionCornerRadius > 0) {
            self.layer.cornerRadius = layout.sectionCornerRadius;
            self.layer.masksToBounds = YES;
        }
    }
}

@end

@implementation SCCollectionViewColorFlowLayout {
    NSMutableArray *_colorAttributesArray;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _colorAttributesArray = [NSMutableArray arrayWithCapacity:0];
        [self registerClass:[UICollectionSectionColorReusableView class] forDecorationViewOfKind:kSCCollectionViewColorBgKind];
    }
    return self;
}

- (void)setSectionBgColor:(UIColor *)sectionBgColor {
    _sectionBgColor = sectionBgColor;
}

- (void)prepareLayout {
    [super prepareLayout];
    NSInteger numberOfSections = self.collectionView.numberOfSections;
    [_colorAttributesArray removeAllObjects];
    for (int i = 0; i < numberOfSections; i++) {
        NSInteger numberOfItems = [self.collectionView numberOfItemsInSection:i];
        if (numberOfItems == 0) {
            continue;
        }
        
        CGFloat headerHeight = 0;
        SCSupplementaryCorner corner = [self supplementaryCorneres:i];
        if (corner.header) {
            UICollectionViewLayoutAttributes *headerAttr = [self layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionHeader atIndexPath:[NSIndexPath indexPathForRow:0 inSection:i]];
            headerHeight = CGRectGetHeight(headerAttr.frame);
        }
        
        UICollectionViewLayoutAttributes *firstAttr = [self layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:i]];
        CGRect sectionFrame = CGRectOffset(firstAttr.frame, 0, -headerHeight);
        UICollectionViewLayoutAttributes *lastAttr = [self layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForRow:numberOfItems-1 inSection:i]];
        sectionFrame = CGRectUnion(sectionFrame, lastAttr.frame);
        if (corner.footer) {
            UICollectionViewLayoutAttributes *footerAttr = [self layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionFooter atIndexPath:[NSIndexPath indexPathForRow:0 inSection:i]];
            sectionFrame.size.height += CGRectGetHeight(footerAttr.frame);
        }
        UIEdgeInsets sectionInset = [self fetchSectionInsets:i];
        if (_bgColorMargin) {
            if (self.scrollDirection == UICollectionViewScrollDirectionHorizontal) {
                sectionFrame.size.height = self.collectionView.frame.size.height-sectionInset.top-sectionInset.bottom;
            } else {
                sectionFrame.size.width = self.collectionView.frame.size.width-sectionInset.left-sectionInset.right;
            }
        } else {
            sectionFrame.origin.x -= sectionInset.left;
            sectionFrame.origin.y -= sectionInset.top;
            if (self.scrollDirection == UICollectionViewScrollDirectionHorizontal) {
                sectionFrame.size.width += sectionInset.left + sectionInset.right;
                sectionFrame.size.height = self.collectionView.frame.size.height;
            } else {
                sectionFrame.size.width = self.collectionView.frame.size.width;
                sectionFrame.size.height += sectionInset.top + sectionInset.bottom;
            }
        }
        
        
        UICollectionViewColorLayoutAttributes *decorationAttributes =
        (UICollectionViewColorLayoutAttributes *)[self layoutAttributesForDecorationViewOfKind:kSCCollectionViewColorBgKind atIndexPath:[NSIndexPath indexPathForItem:0 inSection:i]];
        decorationAttributes.frame = sectionFrame;
        decorationAttributes.zIndex = -1;
        [_colorAttributesArray addObject:decorationAttributes];
    }
}

- (UIEdgeInsets)fetchSectionInsets:(NSInteger)section {
    UICollectionView *view = self.collectionView;
    id <SCCollectionViewColorDelegateFlowLayout>delegate = (id)view.delegate;

    if ([delegate respondsToSelector:@selector(collectionView:layout:insetForSectionAtIndex:)]) {
        return [delegate collectionView:view layout:self insetForSectionAtIndex:section];
    }
    return self.sectionInset;
}

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
    
    NSArray *attributes = [super layoutAttributesForElementsInRect:rect];
    NSMutableArray *allAttributes;
        
    if (_leftFloat) {
        allAttributes = [NSMutableArray arrayWithCapacity:attributes.count];
        UIEdgeInsets sectionInset = UIEdgeInsetsZero;
        CGFloat leftMargin = 0, x = 0;;
        BOOL fetchUnique = NO;
        if (UIEdgeInsetsEqualToEdgeInsets(self.sectionInset, UIEdgeInsetsZero)) {
            fetchUnique = YES;
        } else {
            sectionInset = self.sectionInset;
            x = sectionInset.left;
        }
        NSInteger lastSection = -1;
        for (UICollectionViewLayoutAttributes *attribute in attributes) {
            if (attribute.representedElementCategory == UICollectionElementCategorySupplementaryView) {
                [allAttributes addObject:attribute];
                continue;
            }
            
            
            if (fetchUnique && (lastSection != attribute.indexPath.section)) {
                sectionInset = [self fetchSectionInsets:attribute.indexPath.section];
                x = sectionInset.left;
                leftMargin = 0;
            }
            if (attribute.frame.origin.x == sectionInset.left) {
                x = sectionInset.left; //will add outside loop
                leftMargin = 0;
            } else {
                CGRect newLeftAlignedFrame = attribute.frame;
                newLeftAlignedFrame.origin.x = leftMargin + x;
                attribute.frame = newLeftAlignedFrame;
            }
            
            leftMargin += attribute.frame.size.width + self.minimumInteritemSpacing;
            [allAttributes addObject:attribute];
            lastSection = attribute.indexPath.section;
        }
    } else {
        allAttributes = [NSMutableArray arrayWithArray:attributes];
    }
    
    for (UICollectionViewColorLayoutAttributes *attr in _colorAttributesArray) {
        if (CGRectIntersectsRect(rect, attr.frame)) {
            [allAttributes addObject:attr];
        }
    }
    
    return allAttributes;
}

- (UICollectionViewLayoutAttributes *)layoutAttributesForDecorationViewOfKind:(NSString*)elementKind atIndexPath:(NSIndexPath *)indexPath {
    if (_sectionBgColor) {
        UICollectionViewColorLayoutAttributes *colorAttributes = [UICollectionViewColorLayoutAttributes layoutAttributesForDecorationViewOfKind:kSCCollectionViewColorBgKind withIndexPath:indexPath];
        colorAttributes.sectionBgColor = _sectionBgColor;
        colorAttributes.sectionCornerRadius = _sectionCornerRadius;
        return colorAttributes;
    }
    UICollectionView *view = self.collectionView;
    id <SCCollectionViewColorDelegateFlowLayout>delegate = (id)view.delegate;
    if ([delegate respondsToSelector:@selector(collectionView: layout: colorForSection:)]) {
        UIColor *color = [delegate collectionView:view layout:self colorForSection:indexPath.section];
        UICollectionViewColorLayoutAttributes *colorAttributes = [UICollectionViewColorLayoutAttributes layoutAttributesForDecorationViewOfKind:kSCCollectionViewColorBgKind withIndexPath:indexPath];
        colorAttributes.sectionBgColor = color;
        return colorAttributes;
    }
    return nil;
}

- (SCSupplementaryCorner)supplementaryCorneres:(NSInteger)section {
    UICollectionView *view = self.collectionView;
    id <SCCollectionViewColorDelegateFlowLayout>delegate = (id)view.delegate;
    if ([delegate respondsToSelector:@selector(collectionViewLayout:supplementaryCorner:)]) {
        return [delegate collectionViewLayout:self supplementaryCorner:section];
    } else {
        return _corner;
    }
}

@end
